package cn.edu.nju.oraldefense.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import cn.edu.nju.oraldefense.dao.PaperDao;
import cn.edu.nju.oraldefense.model.Graduate;
import cn.edu.nju.oraldefense.model.Paper;

@Component("paperDao")
public class PaperDaoImpl implements PaperDao {

	HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void save(Paper instance) {
		hibernateTemplate.save(instance);
	}

	public List findAll() {
		String queryString = "from Paper as model order by model.id desc";
		return getHibernateTemplate().find(queryString);
	}

	public Paper findById(int id) {
		Paper instance = (Paper) getHibernateTemplate().get(
				"cn.edu.nju.oraldefense.model.Paper", id);
		return instance;
	}

	public List findByProperty(String propertyName, Object value) {
		// TODO: Test if the list is null;
		String queryString = "from Paper as model where model." + propertyName
				+ "=?";
		System.out.println(queryString);
		return hibernateTemplate.find(queryString, value);
	}

	public Paper findByGraduate(Graduate graduate) {
		List list = findByProperty("graduate", graduate);
		Paper paper = null;
		if (list != null && list.size() > 0)
			paper = (Paper)list.get(0);
		return paper;
	}

	public void update(Paper instance) {
		hibernateTemplate.update(instance);
	}

	public void delete(Paper instance) {
		hibernateTemplate.delete(instance);
	}
}
